% code for averaging SPM's
% just least sqaure
% robust not implemented yet

% NOT tested
% PROCMT User's guide OFFLINE PROCESSING SOFTWARE FOR MAGNETOTELLURIC TIME SERIES, 
% 										A. Ellinghaus, Metronix GmbH, Braunschweig,Germany. 29.5.97     Rev. 2.1
% Latest date 17.06.2003


function[SPM] = AverageSPM(SPMall,ProcDef),

if ProcDef.overlap ==1,  % Overlap of windows cause reduction in dof for FC's
   v=0.818;					 % A correction to this effect is done here
else,
   v=1;
end;

A = size(SPMall);
TLFreq1=ProcDef.TLFreq1;
len=A(2);
fs=ProcDef.GMS05.fs(ProcDef.nband);
par=ProcDef.RadSize(ProcDef.RdBd(ProcDef.nband));
block=ProcDef.block;
for i = 1:A(1),
   for j = 1:A(3),
      for k = 1:A(4),
         SPM.spectra(i).data(j,k) = sum(SPMall(i,:,j,k))/len;
      end;
   end;
   SPM.spectra(i).freq = TLFreq1(i);
   SPM.spectra(i).dof.avgt=len;
   dof = floor(v*2*block*TLFreq1(i)*par/fs);
   if dof < 4,
      dof = 4;
   end;
   SPM.spectra(i).dof.avgf= dof;
end;
 SPM.head.site = ProcDef.file1;
     